package com.springboot.springbootnetty.nettyservice;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

public class MyNettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读接收过来的数据
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {


        System.out.println("服务器读取线程：" + Thread.currentThread().getName());
        System.out.println(ctx.channel().remoteAddress() + ":" + msg);

        ByteBuf buf = (ByteBuf) msg;
        System.out.println("客户端发送消息是：" + buf.toString(StandardCharsets.UTF_8));
        System.out.println("客户端远程地址 ：" + ctx.channel().remoteAddress());
        System.out.println(msg.hashCode());
        System.out.println(buf.hashCode());
        //      super.channelRead (ctx, msg);
    }
        @Override
        public void channelReadComplete (ChannelHandlerContext ctx) throws Exception {
        /*
        writeAndFlush 是write+flush
        将数据写入缓存，并刷新
        一般讲，对发送的数据进行编码
         */
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端1~", CharsetUtil.UTF_8));
        }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {

            //将  evt 向下转型 IdleStateEvent
            IdleStateEvent event = (IdleStateEvent) evt;
            String eventType = null;
            switch (event.state()) {
                case READER_IDLE:
                    eventType = "读空闲";
                    break;
                case WRITER_IDLE:
                    eventType = "写空闲";
                    break;
                case ALL_IDLE:
                    eventType = "读写空闲";
                    break;
            }
//            System.out.println(ctx.channel().remoteAddress() + "--超时时间--" + eventType);
//            System.out.println("服务器做相应处理..");

            //如果发生空闲，我们关闭通道
             ctx.channel().close();

            System.out.println("通道关闭成功！");

        }
//        super.userEventTriggered(ctx, evt);
    }

    /**
         * 处理异常
         *
         * @param ctx
         * @param cause
         * @throws Exception
         */
        @Override
        public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        super.exceptionCaught(ctx, cause);
            ctx.close();
        }
    }
